package main.com.cyz.Queue;

import main.com.cyz.Queue.Bean.MyQueue;

import java.util.Iterator;

/**
 * @author fox
 * @version 1.0
 * @description 手写环形数组队列
 * @date 2024/5/19 11:36
 */
public class MyArrayQueue1<E> implements MyQueue<E>,Iterable<E> {

    private E[] array;
    private int head;
    private int tail;
    private int capacity = 8;

    public MyArrayQueue1() {
        array = (E[]) new Object[capacity + 1];
    }

    public MyArrayQueue1(int capacity) {
        array = (E[]) new Object[capacity + 1];
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {

            int point = head;

            @Override
            public boolean hasNext() {
                return point != tail;
            }

            @Override
            public E next() {
                E value = array[point];
                point = (point + 1) % array.length;
                return value;
            }
        };
    }

    @Override
    public Boolean offer(E value) {
        if (isFull()){
            return false;
        }
        array[tail] = value;
        tail = (tail + 1) % array.length;
        return true;
    }

    @Override
    public E poll() {
        if (isEmpty()){
            return null;
        }
        E value = array[head];
        head = (head + 1) % array.length;
        return value;
    }

    @Override
    public E peek() {
        if (isEmpty()){
            return null;
        }
        return array[head];
    }

    @Override
    public Boolean isEmpty() {
        return head == tail;
    }

    @Override
    public Boolean isFull() {
        return (tail + 1) % array.length == head;
    }
}
